#include "comparator.h"
#include "io430x22x4.h"
//#include "msp430f2274.h"
#include "intrinsics.h"

__interrupt void comparator_isr (void);

static void (* comp_registered_callback_fn)(void) ;

//-------------------------------------
// Comparator initialization
//-------------------------------------
//void comparator_init(pf_t callback_fn){
void comparator_init(void (*callback_fn)() ){
  // register callback function
  comp_registered_callback_fn = callback_fn;
  // -- Comparator
  // OA0CTL0 Comparator 0 control register
  OA0CTL0 |= OAADC0;   // OAADC0=01: OA0OUT connected to pin 8
  OA0CTL0 |= (OAPM0 + OAPM1); // Enable output with fast slew rate
  // OA0CTL0 Comparator 0 control register
  OA0CTL1 |= (OAFBR1 + OAFBR0);  // OAFBRx=011: 10R/6R = 0.6 with OARRIP=0
  OA0CTL1 |= (OAFC1 + OAFC0); //OAFCx=011 comparator

  // --- Vref setup
  // ADC10CTL0 ADC control register 0 
  ADC10CTL0 |= REFOUT;   // VREF externally on pin VREF+.
  ADC10CTL0 &= ~REF2_5V; // Vref = 1.5V
  ADC10CTL0 |= REFON;    // Internar Ref ON 

  //--- Pin configuration
  P2SEL |= 0x0010;//P2SEL_4;  // P2.4 used by periferic (Vref out)
  P2SEL |= 0x0001; //P2SEL_0;  // P2.0 used by periferic (comp in)
  P4SEL |= 0x0008; //P4SEL_3;  // P4.3 used by periferic (comp out)

  //--- I/O interrupt
  P2DIR &= ~0x0002; //P2DIR_1; // P2.1 input
  
  // cuando VCC del micro esta fijo y medimos el consumo de un tercero,
  // hay que detectar High to LOW
  P2IES |= 0x0002; //P2IES_1; // interrupt when HIGH to LOW // 
  // cuando VCC del micro se alimenta de cap y varia
  // hay que detectar LOW to HIGH
  // P2IES &= ~P2IES_1; // interrupt when LOW to HIGH // 
    
  P2IE  |= 0x0002; //P2IE_1;   // Interrupt enable
    return; 
} 



#pragma vector=PORT2_VECTOR   
__interrupt void comparator_isr (void){ 
    comp_registered_callback_fn();           // Execute registered callback function;
    P2IFG &= ~0x0002;//P2IFG_1;
    }

//void comparator_isr (void){ 
//    comp_registered_callback_fn();           // Execute registered callback function;
//    P2IFG &= ~0x0002;//P2IFG_1;
//    }
